from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
import json
import os
import requests,json
import logging
headers = {
    "Content-Type": "application/json",
    "accept": "application/json",
    }
url="http://127.0.0.1:8000/items/"
class Item(BaseModel):
    mobile: list
    description: str

post_web='''
<form name="input" action="/get" method="get">
<center><h2>Welcome</h2></center>
<center><br>Username: <input type="text" name="mobile"></br></center>
<center><br>Password: <input type="text" name="description"></br></center>
<center><br><input type="submit" value="Submit"></br></center>
</form>
'''

location='static'
app = FastAPI()
app.mount('/static', StaticFiles(directory=location), name='static') 

@app.post("/items/")
async def create_item(item: Item):
    dict0={}
    dict0['mobile']=item.mobile
    dict0['description']=item.description
    print('hello:',item,type(item),item.mobile)
    with open("./static/j1.json", "w",encoding="utf-8") as f:
        json.dump(dict0, f,ensure_ascii=False)
    return item


@app.get("/read1/")
async def read1():
    log('信息下载并清空')
    with open("./static/j1.json", "r",encoding="utf-8") as f:
        dict0=json.load(f)
    with open("./static/j1.json", "w",encoding="utf-8") as f:
        json.dump({}, f,ensure_ascii=False)
    return dict0

@app.get("/post1")
async def post1():

    return HTMLResponse(content=post_web)
@app.get("/get")
async def get(mobile,description):
    body = {
      "mobile": mobile.split(';'),
      "description": description
    }
    body = {
      "mobile": [1,2,3],
      "description": description
    }
    body=json.dumps(body)
    print('000000000000')
    try:
        res = requests.post(url=url,headers=headers,data=body,timeout=1)
        #res = requests.get(url='http://www.baidu.com',headers=headers,data=body,timeout=1)
    except:
        print('hhhhhhhhhhhhh')
    print('1111111111')
    log('信息上传'+":"+mobile+":"+description)
    print('2222222222')
    return mobile.split(';'),description
def log(x):
    
    logging.basicConfig(filename='log.txt',level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)
    logger.setLevel(level = logging.INFO)
    handler = logging.FileHandler("./log.txt")
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
     
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
     
    logger.addHandler(handler)
    logger.addHandler(console)
     
    logger.info(x)
    #logger.debug("Do something")
    #logger.warning("Something maybe fail.")
    #logger.info("Finish")
